/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode[]} lists
 * @return {ListNode}
 */
 var mergeKLists = function(lists) {
    let length=lists.length;
    if(length==0){
        return null;
    }
    let head=0,end=length-1;
    while(end!=0){
        if(head>=end){
            head=0;
        }
        lists[head]=mergeList(lists[head],lists[end]);
        head++;
        end--;
    }
    return lists[0];
    function mergeList (l1, l2) {
        let head = new ListNode();
        let p = head;
        while (l1 && l2) {
            if (l1.val < l2.val) {
                p.next = l1;
                l1 = l1.next;
            }
            else {
                p.next = l2;
                l2 = l2.next;
            }
            p = p.next;
        }
        p.next = l1 || l2;
        return head.next;
    }
};
/*  var mergeKLists = function(lists) {
    let length=lists.length;
    if(length==0){
        return null;
    }
    let newlist=lists[0];
    for(let i=1;i<length;i++){
        newlist=mergeList(newlist,lists[i]);
    }
    return newlist;
    function mergeList (l1, l2) {
        let head = new ListNode();
        let p = head;
        while (l1 && l2) {
            if (l1.val < l2.val) {
                p.next = l1;
                l1 = l1.next;
            }
            else {
                p.next = l2;
                l2 = l2.next;
            }
            p = p.next;
        }
        p.next = l1 || l2;
        return head.next;
    }
}; */